package com.wy.util.Http;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.jsoup.select.Elements;

import com.wy.entity.Chapter;

public class CatchBookUtil {
	
	/***************************************************************
	 * 						 www.59to.com						   *
	 ***************************************************************/
	/**
	 * 将Elements对象解析成List<Chapter>集合
	 * @param elements	章节标签元素集合
	 * @return List<Chapter>
	 */
	public static List<Chapter> parseElementsToCharpterList(Elements elements){
		String targetUrl = null;
		String title = null;
		List<Chapter> list = new ArrayList<Chapter>();
		
		if(!elements.isEmpty() && elements.size() >0){
			for(int i=0;i<elements.size();i++){
				Chapter c = new Chapter();
				targetUrl = elements.get(i).attr("href");
				if(targetUrl != null && !targetUrl.trim().equals("")){
					title = elements.get(i).text();
					c.setId(i);
					c.setTitle(title);
					c.setTargetUrl(targetUrl);
					list.add(c);
				}
			}
		}
		return list;
	}
	/**
	 * 解析小说目录链接，得到List<Chapter>集合
	 * @param catalogUrl 小说目录页面URL
	 * @param webName 网站名称；如：www.59to.com
	 * @return List<Chapter>
	 */
	public static List<Chapter> getChapterListByCatalogUrl(String catalogUrl,String encode, String query){
		String html = HttpClientUtil.getHtmlByURL(catalogUrl,encode);
		if(html == null || html.trim().equals("")){
			return null;
		}
		List<Chapter> list = new ArrayList<Chapter>();
		list = parseElementsToCharpterList(HttpClientUtil.parseHtmlToElements(html, query));
		// 章节排序
        Collections.sort(list, new Comparator<Chapter>() {
            public int compare(Chapter c1, Chapter c2) {
                return c1.getId().compareTo(c2.getId());
            }
	    });
		return list;
	}
	/**
	 * 得到章节内容
	 * @param chapterUrl 章节URL
	 * @param query 查询条件
	 * @return String 内容
	 */
	public static String getChapterContentByUrl(String chapterUrl, String encode, String query){
		
		String html = HttpClientUtil.getHtmlByURL(chapterUrl, encode);
		if(html == null || html.trim().equals("")){
			return null;
		}
		return HttpClientUtil.parseHtmlToElements(html, query).get(0).html();
	}
}
